package com.ypan.monitor.osutils;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

//CPU的使用率
public class CPULoad {
	public static long idle = 0L;
	public static long total = 0L;
	public long usage = 0L;

	public CPULoad() {
		refreshUsage();
	}

	public long getUsage() {
		return usage;
	}

	public void refreshUsage() {
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(
					new FileInputStream("/proc/stat")));
			String str = br.readLine();
			br.close();
			String[] arrayStrs = str.split(" ");
			long total2 = Long.parseLong(arrayStrs[2])
					+ Long.parseLong(arrayStrs[3])
					+ Long.parseLong(arrayStrs[4])
					+ Long.parseLong(arrayStrs[5])
					+ Long.parseLong(arrayStrs[6])
					+ Long.parseLong(arrayStrs[7])
					+ Long.parseLong(arrayStrs[8]);
			long idle2 = Long.parseLong(arrayStrs[5]);
			usage = (long) (100.0f - 100.0f * (float) (idle2 - idle)
					/ (float) (total2 - total));
			total = total2;
			idle = idle2;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
